<template>
  <div class="register-wrapper">
    <div class="register-container">
      <div class="form-header">
        <h2>用户注册</h2>
        <p>请填写以下信息完成注册</p>
      </div>
      <form @submit.prevent="handleRegister" class="floating-form">
        <div class="input-group">
          <input id="email" v-model.trim="registerForm.email" type="email" autocomplete="off" @input="validateInput" required />
          <label for="email">邮箱</label>
          <span class="highlight"></span>
        </div>
        <div class="input-group">
          <input id="verificationCode" v-model.trim="registerForm.verificationCode" type="text" autocomplete="off" @input="validateInput" required />
          <label for="verificationCode">验证码</label>
          <button type="button" class="get-code-btn" :disabled="isCountingDown" @click="getVerificationCode">
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </button>
          <span class="highlight"></span>
        </div>
        <div class="input-group">
          <input id="username" v-model.trim="registerForm.username" type="text" autocomplete="off" @input="validateInput" required />
          <label for="username">用户名</label>
          <span class="highlight"></span>
        </div>
        <div class="input-group">
          <input id="password" v-model.trim="registerForm.password" type="password" autocomplete="off" @input="validateInput" required />
          <label for="password">密码</label>
          <span class="highlight"></span>
        </div>
        <div class="error-message" v-if="errorMsg">{{ errorMsg }}</div>
        <button type="submit" class="submit-btn" :disabled="!isFormValid">
          <span>注册</span>
          <i class="arrow-icon"></i>
        </button>
        <div class="form-footer">
          <span>已有账号？</span>
          <router-link to="/">立即登录</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import request from "@/utils/request.js";
import { ElMessage } from 'element-plus';

const router = useRouter();

// 表单数据
const registerForm = reactive({
  email: '',
  verificationCode: '',
  username: '',
  password: ''
});

const errorMsg = ref('');
const isFormValid = ref(false);
const countdown = ref(0);
const isCountingDown = ref(false);

// 输入验证
const validateInput = () => {
  const { email, verificationCode, username, password } = registerForm;
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

  if (
      email &&
      verificationCode &&
      username &&
      password &&
      emailPattern.test(email)
  ) {
    isFormValid.value = true;
    errorMsg.value = '';
  } else {
    isFormValid.value = false;
    if (!emailPattern.test(email)) {
      errorMsg.value = '请输入有效的邮箱地址';
    }
  }
};

// 获取验证码
const getVerificationCode = async () => {
  const { email } = registerForm;
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

  if (!emailPattern.test(email)) {
    errorMsg.value = '请输入有效的邮箱地址';
    return;
  }

  try {
    await request.post('/api/', { email });
    ElMessage.success('验证码已发送，请查收邮箱');
    startCountdown();
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('获取验证码失败，请稍后重试');
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  isCountingDown.value = true;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      clearInterval(timer);
      isCountingDown.value = false;
    }
  }, 1000);
};

// 注册处理
const handleRegister = async () => {
  validateInput();
  if (!isFormValid.value) return;

  try {
    const response = await request.post('/api/register', registerForm);
    if (response.data === true) {
      ElMessage.success('注册成功，请登录');
      router.push('/home');
    } else {
      errorMessage('注册失败，请稍后重试');
    }
  } catch (error) {
    console.error('注册失败:', error);
    errorMessage('注册失败，请重试');
  }
};

// 错误提示
const errorMessage = (text) => {
  errorMsg.value = text;
  setTimeout(() => {
    errorMsg.value = '';
  }, 3000);
};
</script>

<style scoped>
.register-wrapper {
  min-height: 93.5vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.register-container {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 20px;
  padding: 40px;
  padding-right: 80px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  color: #2c3e50;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 700;
}

.form-header p {
  color: #95a5a6;
  font-size: 16px;
}

.floating-form .input-group {
  position: relative;
  margin-bottom: 30px;
}

.input-group input {
  width: 100%;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: transparent;
}

.input-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: white;
  padding: 0 5px;
  color: #95a5a6;
  font-size: 16px;
  transition: all 0.3s ease;
  pointer-events: none;
}

.input-group input:focus,
.input-group input:valid {
  border-color: #3498db;
}

.input-group input:focus + label,
.input-group input:valid + label {
  top: 0;
  font-size: 14px;
  color: #3498db;
}

.get-code-btn {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.get-code-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 15px;
  margin-left: 15px;
  background: linear-gradient(to right, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.arrow-icon {
  border: solid white;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(-45deg);
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  color: #95a5a6;
}

.form-footer a {
  color: #3498db;
  text-decoration: none;
  margin-left: 5px;
  font-weight: 600;
}

.form-footer a:hover {
  text-decoration: underline;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  text-align: center;
  margin-bottom: 20px;
}

@media (max-width: 480px) {
  .register-container {
    padding: 20px;
  }

  .form-header h2 {
    font-size: 24px;
  }

  .input-group input {
    padding: 12px;
  }
}

@media (max-width: 768px) {
  .register-container {
    max-width: 400px;
    padding: 30px;
  }

  .form-header h2 {
    font-size: 28px;
  }

  .form-header p {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 20px;
    margin: 10px;
    max-width: 100%;
  }

  .form-header h2 {
    font-size: 24px;
  }

  .form-header p {
    font-size: 14px;
  }

  .input-group input {
    padding: 12px;
    font-size: 14px;
  }

  .input-group label {
    font-size: 14px;
  }

  .submit-btn {
    padding: 12px;
    font-size: 16px;
  }
}

@media (max-width: 320px) {
  .register-container {
    padding: 15px;
  }

  .form-header h2 {
    font-size: 20px;
  }

  .input-group {
    margin-bottom: 20px;
  }
}
</style>
